package fr.uniscol.siecle.parsers;

import java.io.File;
import java.text.ParseException;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import fr.uniscol.siecle.model.Communs;
import fr.uniscol.siecle.model.FichierSIECLE;
import fr.uniscol.siecle.model.Parametres;

public abstract class IFichierSIECLEParser {

	public static Logger log = Logger.getLogger(IFichierSIECLEParser.class);
	
	public FichierSIECLE parseFichier(File fXml, ParsingResults results) throws ParseException{
		
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		FichierSIECLE model = null;
		try {
			doc = builder.build(fXml);
			
			Parametres params = readParametres(doc, results);
			
			model = buildModel(doc, results);
			
			if(model != null){
				model.setParametres(params);
			}
			
		} catch (Exception e) {
			log.error(e);;
			e.printStackTrace();
			
			throw new ParseException(e.getMessage(), 0);
		}
		
		return model;
	}
	
	public Parametres readParametres(Document doc, ParsingResults results){
		
		Parametres param = new Parametres();
		
		Element eParams = doc.getRootElement().getChild("PARAMETRES");
		param.setUaj(eParams.getChildText("UAJ"));
		param.setDateExport(eParams.getChildText("DATE_EXPORT"));
		param.setAnneeScolaire(eParams.getChildText("ANNEE_SCOLAIRE"));
		param.setHorodatage(eParams.getChildText("HORODATAGE"));
		
		log.debug("UAJ=" + param.getUaj());
		log.debug("DATE_EXPORT=" + param.getDateExport());
		log.debug("ANNEE_SCOLAIRE=" + param.getAnneeScolaire());
		log.debug("HORODATAGE=" + param.getHorodatage());
		
		return param;
	}
	
	public abstract FichierSIECLE buildModel(Document doc, ParsingResults results);
}
